package com.cloudwise.service.impl;

import com.cloudwise.dao.UserDao;
import com.cloudwise.dao.UserRoleDao;
import com.cloudwise.entity.User;
import com.cloudwise.entity.UserRole;
import com.cloudwise.entity.UserVo;
import com.cloudwise.service.UserService;
import com.cloudwise.shiro.ShiroUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户信息表(User)表服务实现类
 *
 * @author makejava
 * @since 2020-12-17 10:18:04
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Resource
    UserRoleDao userRoleDao;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer userId) {
        return this.userDao.queryById(userId);
    }

    @Override
    public User queryByUsername(String username) {
        return userDao.queryByUsername(username);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<User> queryAllByLimit(int offset, int limit) {
        return this.userDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        this.userDao.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        this.userDao.update(user);
        return this.queryById(user.getUserId());
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return this.userDao.deleteById(userId) > 0;
    }

    @Override
    public List<User> queryAllByConditionAndLimit(User user, int offset, int limit) {
        return userDao.queryAllByConditionAndLimit(user,offset,limit);
    }

    @Override
    public List<UserVo> queryAllUserVoByConditionAndLimit(User user, int offset, int limit) {
        return userDao.queryAllUserVoByConditionAndLimit(user,offset,limit);
    }

    @Override
    public long getCount(User user) {
        return userDao.getCount(user);
    }

    /**
     * @create by: Teacher陈
     * @description: 更新用户和角色中间表
     * @create time: 2020/7/19 13:37
     */
    private boolean updateRoleUser(User user,String roleIds) {
        if ( roleIds != null) {
            //删除此用户原有的角色
             userRoleDao.deleteById(user.getUserId());
            //添加此用户关联的新角色
            String[] strings = roleIds.split(",");
            for (String string : strings) {
                if (string != null && string != "") {
                    Integer roleID = Integer.parseInt(string);
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getUserId());
                    userRole.setRoleId(roleID);
                    userRoleDao.insert(userRole);
                }
            }
            return true;
        }
        return false;
    }
    @Override
    public boolean saveUserAndSalt(User user) {
        //获取从页面传入的角色id,因为salt是在后台生成，所有由salt属性传入角色id的集合
        String roleIds = user.getSalt();
        //生成随机码作为salt
        String salt = UUID.randomUUID().toString();
        //获取明文密码
        String message = user.getPassword();
        //获取密文密码
        String encryption = ShiroUtil.encryptionBySalt(salt, message);
        //设置user的密码属性
        user.setPassword(encryption);
        //设置user对象的盐值属性
        user.setSalt(salt);
        //将用户保存到数据库
        Integer insert = userDao.insert(user);
        //如果插入成功，并且页面传入的角色id不为空
        return updateRoleUser(user,roleIds);
    }

    @Override
    public boolean updateUserAndSalt(User user) {
        String roleIds = user.getSalt();
        //将用户保存到数据库
        user.setSalt(null);
        Integer update = userDao.update(user);
        //如果插入成功，并且页面传入的角色id不为空
        if(update>0){
            boolean b = updateRoleUser(user, roleIds);
            if(b){
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean resetPassword(User user) {
        //生成随机码作为salt
        String salt = UUID.randomUUID().toString();
        //获取明文密码
        String message = user.getPassword();
        //获取密文密码
        String encryption = ShiroUtil.encryptionBySalt(salt, message);
        //设置user的密码属性
        user.setPassword(encryption);
        //设置user对象的盐值属性
        user.setSalt(salt);
        //将用户保存到数据库
        Integer reset = userDao.resetPassword(user);
        if(reset>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateBatchById(List<User> userList) {
        int i = userDao.updateBatchById(userList);
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public Map getCountUserByDept() {
        Map map = new HashMap();
        //map需要封装x轴坐标和y轴坐标
        List<Map> mapList = userDao.getCountUserByDept();
        //定义x轴坐标
        String [] deptNames=new String[mapList.size()];
        //定义y轴坐标
        Integer [] nums= new Integer[mapList.size()];
        for (int i = 0; i < mapList.size(); i++) {
            deptNames[i]=mapList.get(i).get("deptName").toString();
            nums[i]=Integer.parseInt(mapList.get(i).get("nums").toString());
        }
        map.put("deptNames",deptNames);
        map.put("nums",nums);
        return map;
    }
}